import Vue from 'vue';
import Router from 'vue-router';
import HomeView from '@/views/HomeView.vue';
import BookStore from '@/views/BookStore.vue';
import BookShelf from '@/views/BookShelf.vue'; // 引入书架页面组件
import ViewTop from '@/views/ViewTop.vue';
import Book from '@/views/book/Book.vue';
import Reader from '@/views/book/Reader.vue';
import FriendPage from '@/views/FriendPage.vue';
import LoginView from '@/views/LoginView.vue';  
import RegisterView from '@/views/RegisterView.vue';
import BookSearch from '@/views/BookSearch.vue';
import AuthorView from '@/views/AuthorView.vue';
import test from '@/views/test.vue';
import ChatPage from '@/views/ChatPage.vue';
Vue.use(Router);
// 获取原型对象push函数
const originalPush = Router.prototype.push

// 获取原型对象replace函数
const originalReplace = Router.prototype.replace

// 修改原型对象中的push函数
Router.prototype.push = function push(location){
return originalPush.call(this , location).catch(err=>err)
}

// 修改原型对象中的replace函数
Router.prototype.replace = function replace(location){
return originalReplace.call(this , location).catch(err=>err)
}

const router= new Router({
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'Login',
      component: LoginView //登录
    },
    {
      path: '/register',
      name: 'Register',
      component: RegisterView //注册
    },
    {
      path: '/homeview',
      name: 'HomeView',
      component: HomeView
    },
    {
      path: '/bookstore',
      name: 'BookStore',
      component: BookStore // 添加书库页面路由
    },
    {
      path: '/bookshelf',
      name: 'BookShelf',
      component: BookShelf // 添加书架页面路由
    },
    {
      path: '/viewtop',
      name: 'ViewTop',
      component: ViewTop // 
    },
    {
      path: '/book',
      name: 'Book',
      component: Book
    },
    {
      path: '/reader',
      name: '/Reader',
      component: Reader
    },
    {
      path: '/friendpage',
      name: 'FriendPage',
      component: FriendPage
    },
    {
      path: '/booksearch',
      name: 'BookSearch',
      component: BookSearch
    },
    {
      path:'/authorview',
      name:'AuthorView',
      component:AuthorView
    },
    {
      path:'/test',
      name:'test',
      component:test
    },
    {
      path:'/chatpage',
      name:'ChatPage',
      component:ChatPage
    }
  ],
  
});

// 导航守卫
// 使用 router.beforeEach 注册一个全局前置守卫，判断用户是否登陆
router.beforeEach((to, from, next) => {
  if (to.path === '/login' || to.path === '/register') {
    next();
  } else {
    let authentication = sessionStorage.getItem('authentication');
    console.log(authentication);
    if (authentication === null || authentication === '') {
      next('/login');
    } else {
      next();
    }
  }
});
export default router;